import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as mqtt from 'mqtt'
@Injectable()
export class MqttService {
    private client:mqtt.MqttClient;



    constructor(
        private configService:ConfigService
    ) {

    }

    connect() :Promise<void>{
        const conf = this.configService.get('mqtt')

        return new Promise((resolve, reject) => {
            this.client = mqtt.connect(conf.options)
            this.client.on('disconnect', () => {
                console.log('mqtt重连')
                this.client.reconnect()
            }).on('error', error => {
                reject(error)
            }).on('connect', () => {
                resolve()
            })
        })

    }

    subscribe(topic:string|string[], qos:0|1|2) :Promise<void>{
        
        return new Promise((resolve, reject) => {
            this.client.subscribe(topic, {qos}, (error, granted) => {
                error ? reject(error) : resolve()
            })
        })
    }

    message(callback : (topic:string, msg:any) => void) {
        this.client.on('message', (topic, message) => {
            callback(topic, JSON.parse(message.toString()))
        })
    }

    publish(topic:string, params:Object) {
        this.client.publish(topic, JSON.stringify(params), {
            qos : 2
        })
    }
}
